import { ref } from 'vue'
import { useManager } from './useManager'
import { fetchManagers, fuzzyVips, SAManager, delManager } from '../axioser'
import md5 from 'md5'
import { ElMessage } from 'element-plus'

const { managerOptions } = useManager()
export function useManagerAccounts() {
  // 账号配置
  const accountOptions = {
    ...managerOptions,
    password: '',
    self_password: '',
  }
  // 当前选中管理员
  const currentManagerSelected = ref({ ...accountOptions })
  //当前选中的管理组
  const currentManagersSelected = ref([])
  // 管理组信息
  const managerList = ref([])
  // BindVip列表
  const bindVips = ref({
    list: [],
    isLoading: true,
  })
  // 获取BindVips信息
  const getBindVips = async keyword => {
    try {
      const {
        data: {
          data: { list },
        },
      } = await fuzzyVips({ keyword })
      bindVips.value.list = list
      bindVips.value.isLoading = false
    } catch (error) {
      console.error(error)
    }
  }
  // 获取管理组信息
  const getManagersInfo = async () => {
    try {
      const {
        data: {
          data: { list, total },
        },
      } = await fetchManagers()
      managerList.value = list
    } catch (error) {
      console.error(error)
    }
  }
  // SA回调函数(S->设置，A->增加)
  const SAConfirmYes = async (mode, dialog = undefined) => {
    let {
      uid,
      name,
      privilege_level,
      state,
      password,
      self_password,
      bind_vip,
    } = currentManagerSelected.value
    const {
      data: { code },
    } = await SAManager(mode, {
      uid,
      username: name,
      privilege_level,
      state,
      password: password ? md5(password) : undefined,
      self_password: self_password ? md5(self_password) : undefined,
      bind_vip,
    })
    if (code === 2000) {
      ElMessage.success(`管理员${name + (mode ? '新建' : '编辑')}成功`)
      dialog && (dialog.show = false)
      currentManagerSelected.value = accountOptions
      getManagersInfo()
    }
  }
  // 删除管理员回调
  const delConfirmYes = async list => {
    const {
      data: { code },
    } = await delManager({ list })
    if (code === 2000) {
      ElMessage.success(`管理员删除成功`)
      currentManagerSelected.value = accountOptions
      getManagersInfo()
    }
  }
  return {
    accountOptions,
    currentManagerSelected,
    currentManagersSelected,
    bindVips,
    managerList,
    getManagersInfo,
    getBindVips,
    SAConfirmYes,
    delConfirmYes,
  }
}
